package com.lagou.filter;

import com.lagou.util.HttpResponseStatusUtil;
import com.lagou.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;



@Slf4j
@Component
@RefreshScope
public class AuthorizeFilter extends HttpResponseStatusUtil implements GlobalFilter, Ordered {

    @Reference
    private IUserService userService;

    @Value("${api.exclude}")
    private String[] excludePaths;


    @Value("${config.cookie.name}")
    private String accessToken;
    @Value("${config.response.message.unauthorize}")
    private String unauthorizeText;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        for (String exclude : excludePaths) {
            if (path.toLowerCase().contains(exclude)) {
                return chain.filter(exchange);
            }
        }


        List<String> cookies = request.getHeaders().get(accessToken);

       if (CollectionUtils.isEmpty(cookies)){
           log.info("====>>>> request path: " + path + " need authorize,accessToken is null ===> result is fail!");
           return responseStatusAndMessage(response, HttpStatus.UNAUTHORIZED, unauthorizeText);
       }
        String token = cookies.get(0);
        String email = userService.getEmailByToken(token);
        if (Objects.isNull(email)) {
            log.info("====>>>> request path: " + path + " need authorize, result is fail!");
            return responseStatusAndMessage(response, HttpStatus.UNAUTHORIZED, unauthorizeText);
        }

        log.info("====>>>> request path: " + path + " need authorize, result is pass!");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
